package org.mysfit.ctp4j.core.service.impl;

import org.mysfit.ctp4j.api.vo.OrderInsertVO;
import org.mysfit.ctp4j.api.vo.QuoteInsertVO;
import org.mysfit.ctp4j.core.MyCThostFtdcTraderSpi;
import org.mysfit.ctp4j.core.service.CommonService;
import org.mysfit.ctp4j.core.service.TradeService;
import org.mysfit.ctp4j.infra.pojo.CtpConfig;
import org.mysfit.ctp4j.infra.pojo.CtpUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import ctp.thosttraderapi.CThostFtdcTraderApi;
import ctp.thosttraderapi.THOST_TE_RESUME_TYPE;

/**
 * 
 * @author long.gf
 * @since 2022-12-06
 *
 */
@Service
public class TradeServiceImpl implements TradeService {
	private static final Logger LOGGER = LoggerFactory.getLogger(TradeServiceImpl.class);

	@Autowired
	private CommonService commonService;
	
	@Override
	public void doOrder(String investorId, OrderInsertVO params) {
		CtpConfig ctpConfig = commonService.getConfig();
		CtpUser currCtpUser = commonService.getUser(investorId);
		CThostFtdcTraderApi tradeApi = CThostFtdcTraderApi.CreateFtdcTraderApi();
		MyCThostFtdcTraderSpi traderSpi = new MyCThostFtdcTraderSpi(currCtpUser, tradeApi, this, params);
		tradeApi.RegisterSpi(traderSpi);
		tradeApi.RegisterFront(ctpConfig.getTradeFront());
		tradeApi.Init();
		tradeApi.Join();
	}

	@Override
	public void addData4Order(Object data) {
		LOGGER.info("记录报单结果: {}", data);
	}

	@Override
	public void doQuote(String investorId, QuoteInsertVO params) {
		CtpConfig ctpConfig = commonService.getConfig();
		CtpUser currCtpUser = commonService.getUser(investorId);
		CThostFtdcTraderApi traderApi = CThostFtdcTraderApi.CreateFtdcTraderApi();
		MyCThostFtdcTraderSpi traderSpi = new MyCThostFtdcTraderSpi(currCtpUser, traderApi, this, params);
		traderApi.RegisterSpi(traderSpi);
		traderApi.RegisterFront(ctpConfig.getTradeFront());
		traderApi.SubscribePublicTopic(THOST_TE_RESUME_TYPE.THOST_TERT_QUICK);
		traderApi.SubscribePrivateTopic(THOST_TE_RESUME_TYPE.THOST_TERT_QUICK);
		traderApi.Init();
	}

	@Override
	public void addData4Quote(Object data) {
		LOGGER.info("记录报价结果: {}", data);
	}

}
